﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;

namespace net.veekee.common.data.csv
{
    public class CSVWriterFile : ACSVFile
    {
        private StreamWriter sw = null;

        public override bool IsValid
        {
            get
            {
                return this.sw != null;
            }
        }

        public CSVWriterFile(String filename, char separator = ';', bool append = false)
            : base(filename, separator)
        {
            this.LoadFile(Encoding.Default, append);
        }

        public CSVWriterFile(String filename, Encoding encode, char separator = ';', bool append = false)
            : base(filename, separator)
        {
            this.LoadFile(encode, append);
        }

        private void LoadFile(Encoding encode, bool append)
        {
            try
            {
                if (System.IO.File.Exists(this.fileName))
                {
                    if (!append)
                    {
                        Log.GetInstance().Debug("{0} will be overwritten", this.fileName);
                        System.IO.File.Delete(this.fileName);
                    }
                    else
                    {
                        Log.GetInstance().Debug("{0} will be appened", this.fileName);
                    }
                }
                this.sw = new StreamWriter(this.fileName, append, encode);
                this.SelectSheet(0);
            }
            catch (Exception e)
            {
                Log.GetInstance().Error(e.ToString());
            }
        }

        public override void SetLine(ulong line, IEnumerator items)
        {
            StringBuilder sb = new StringBuilder();
            String separator = "";
            while(items.MoveNext())
            {
                sb.Append(separator + this.RemoveDisallowedChars(items.Current.ToString()));
                separator = this.fieldSeparator.ToString();
            }
            sw.WriteLine(sb.ToString());
            sw.Flush();
        }

        public override void SetCell(ulong line, int column, Object item)
        {
            throw new NotImplementedException();
        }

        public override  void Save()
        {
            if (!this.IsValid)
                return;
            this.sw.Close();
        }

        public override void Dispose()
        {
            this.Save();
            this.sw = null;
        }
    }
}
